<script setup>
import { ref, nextTick, defineEmits } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  roleMgrUpdateStatusService,
  roleMgrAddService,
  menuMgrUpdateService,
  menuMgrAddService,
} from "@/api";
import { useUserStore } from "@/stores";

// 使用用户存储模块
const userInfo = useUserStore();
// 抽屉的可见性状态
const visibleDrawer = ref(false);
// 默认表单数据
const defaultForm = {
  component: "",
  createTime: "",
  id: 0,
  isDeleted: 1,
  name: "",
  parentId: 0,
  sortValue: 0,
  status: 1,
  updateTime: "",
  nameCopy: "顶级菜单",
};
// 表单模型，用于数据绑定和操作
const formModel = ref({ ...defaultForm });

// 表单规则
const rules = {
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  component: [
    { required: true, message: "请输入路由名称", trigger: "blur" },
    {
      pattern: /^[^\u4e00-\u9fa5\s]{4,}$/,
      message: "请输入一个至少4个字符,不包含中文或空格的用户名。",
      trigger: "blur",
    },
  ],
};

// 打开抽屉函数------start
let titleDrawer = ref("编辑菜单");
let operateType = ref("add");
/**
 * 打开抽屉函数，根据传入的行数据和操作类型，决定是编辑、添加还是角色分配操作
 * @param {Object} row - 行数据
 * @param {String} operate - 操作类型
 */
const open = async (row, operate) => {
  operateType.value = operate;
  visibleDrawer.value = true;
  if (operate === "edit") {
    formModel.value = row;
    titleDrawer.value = "编辑菜单";
  }
  if (operate === "add") {
    console.log("添加子菜单");
    if (row) {
      let {
        component,
        createTime,
        id,
        isDeleted,
        name,
        parentId,
        sortValue,
        status,
        updateTime,
      } = row;
      formModel.value = {
        component: "",
        createTime,
        id,
        isDeleted,
        name: "",
        parentId,
        sortValue,
        status,
        updateTime,
        nameCopy: name,
      };
    }

    if (!row) {
      formModel.value = { ...defaultForm };
    }
    titleDrawer.value = "添加子菜单";
  }
};
defineExpose({ open });
// 打开抽屉函数------end

// 添加或编辑操作-------start

let loadingAdd = ref(false); // 添加和编辑操作的加载状态

const formRef = ref(); // 表单引用，用于表单验证和提交

// 发送到父组件的成功事件
const emit = defineEmits(["success"]);
/**
 * 提交表单数据，根据是否有ID判断是进行编辑还是添加操作
 * @param {String} state - 表单状态（已发布或草稿）
 */
const onSubmit = async (state) => {
  await formRef.value.validate(); // 验证表单
  loadingAdd.value = true;
  try {
    if (operateType.value == "edit") {
      let updateData = {
        id: formModel.value.id,
        parentId: formModel.value.parentId,
        name: formModel.value.name,
        component: formModel.value.component,
        status: formModel.value.status,
      };
      let res = await menuMgrUpdateService(updateData);
      ElMessage.success("编辑成功");
      visibleDrawer.value = false;
      emit("success", "edit");
    }

    if (operateType.value == "add") {
      let addData = {
        name: formModel.value.name,
        parentId: formModel.value.id,
        sortValue: 0,
        status: formModel.value.status,
        component: formModel.value.component,
      };
      let res = await menuMgrAddService(addData);
      ElMessage.success("添加成功");
      visibleDrawer.value = false;
      emit("success", "add");
    }
  } catch (error) {
    console.log(error);
  } finally {
    loadingAdd.value = false;
  }
};
// 添加或编辑操作-------end

const changeStatus = () => {
  formModel.value.status = formModel.value.status == 0 ? 1 : 0;
};
</script>

<template>
  <!-- 抽屉组件，用于编辑和添加用户 -->
  <el-dialog
    v-model="visibleDrawer"
    :title="titleDrawer"
    width="30%"
    style="padding: 40px"
  >
    <!-- 表单组件，用于输入菜单信息 -->
    <el-form
      :model="formModel"
      :rules="rules"
      ref="formRef"
      label-position="top"
    >
      <el-form-item
        label="所属父级菜单"
        prop="nameCopy"
        v-if="operateType == 'add'"
      >
        <el-input
          v-model="formModel.nameCopy"
          autocomplete="off"
          :disabled="true"
          placeholder="请输入父级菜单"
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input
          v-model="formModel.name"
          placeholder="请输入菜单名称"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="路由名称" prop="component">
        <el-input
          v-model="formModel.component"
          placeholder="请输入路由名称"
        ></el-input>
      </el-form-item>
      <!-- 用户状态切换开关，仅在编辑操作时显示 -->
      <!-- switch组件加上change事件就会报错 -->
      <el-form-item label="状态" prop="status" v-if="operateType == 'edit'">
        <el-switch
          :model-value="formModel.status == 1 ? true : false"
          @change="changeStatus()"
        />
      </el-form-item>
    </el-form>
    <!-- 提交表单按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visibleDrawer = false">Cancel</el-button>
        <el-button
          type="primary"
          :icon="Plus"
          :loading="loadingAdd"
          @click="onSubmit('已发布')"
          >提交</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-input {
  max-width: 500px;
}
</style>
